package com.grgbanking.it.system.service.impl;


import java.util.ArrayList;
import java.util.List;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.grgbanking.it.common.entity.PageQuery;
import com.grgbanking.it.common.json.JSONHelper;
import com.grgbanking.it.common.util.HibernateUtil;
import com.grgbanking.it.system.dao.IMRoleResourceDao;
import com.grgbanking.it.system.dao.IRoleDao;
import com.grgbanking.it.system.entity.MRoleResource;
import com.grgbanking.it.system.entity.Role;
import com.grgbanking.it.system.service.IRoleService;

/**
 * 角色管理
 * 
 * RoleService
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2014-12-18 上午9:44:38
 * 
 * @version 1.0.0
 *
 */
@Service
public class RoleService implements IRoleService {
	@Autowired
	private IRoleDao<Role, Integer> roleDao;
	@Autowired
	private IMRoleResourceDao<MRoleResource, Integer> roleResourceDao;

	@Override
	public String findByIdToJson(Integer id) throws Exception {
		Role role = (Role) HibernateUtil.loadLazyData(roleDao.findById(id), Role.class);
		return JSONHelper.convertObjectForForm(role);
	}

	@Override
	public void saveOrUpdate(Role role) throws Exception {
		roleDao.saveOrUpdate(role);
	}

	@Override
	public String findByPageToJson(PageQuery query,String username, String key)
			throws Exception {
		StringBuffer sql = new StringBuffer("select r.*,case when m.id is null then 0 else 1 end checked\n ");
		sql.append("from role r left join m_user_role m on r.id=m.role_id and m.username='").append(username).append("'\n");
		sql.append("where r.state<>0 ");
		List<?> list = roleDao.pageBySQL(sql.toString(), query.getStart(), query.getLimit());
		
		return JSONHelper.convertToGrid(roleDao.getTotalBySQL(sql.toString()), list);
	}

	@Override
	public void delete(Integer id) throws Exception {
		roleDao.virtualDelete(id);
	}

	/**
	 * 为角色分配资源
	 * distributeResources
	 * 
	 * @param id
	 * @param json
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public void updateDistributeResources(Integer id, String resourceIds)
			throws Exception {
		StringBuffer hql = new StringBuffer("delete MRoleResource t where t.roleId=");
		hql.append(id);
		roleResourceDao.executeHQL(hql.toString());
		if(StringUtils.isNotEmpty(resourceIds)){
			
			List<MRoleResource> all = new ArrayList<MRoleResource>();
			String[] ids = resourceIds.split(",");
			for (int i = 0; i < ids.length; i++) {
				if(ids[i].equals("root")){
					continue;
				}
					
	            MRoleResource roleResource = new MRoleResource();
	            roleResource.setRoleId(id);
	            roleResource.setResourceId(Integer.valueOf(ids[i]));
	            all.add(roleResource);
			}
			
			roleResourceDao.save(all);
		}
		
	}
	
	
}